// pages/order/addressAdd/addressAdd.js
import Toast from '../../../vant/toast/toast';
import md5 from '../../../utils/md5.js';
import { setRecipients, textRecognition } from '../../../utils/api/index.js';
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    recipientId: 0,
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    recipientName: '',
    phoneNumber: '',
    region: [],
    addressParseStr: '',
    access_token: '',
    discernFlag: true,
    showPicker: false,
    title: '新增收件人',
    recipientType: "USER",//果农收件人信息
    isFocus: false,//未聚焦
    isDisabled: true,

    showOnSureDialog: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.data) {
      const data = JSON.parse(options.data);
      this.setData({
        recipientId: data.recipientid,
        province: data.province,
        city: data.city,
        district: data.district,
        detailAddress: data.detailaddress,
        recipientName: data.recipientname,
        phoneNumber: data.phonenumber,
        region: [data.province, data.city, data.district],
        title: '编辑收件人',
      });
    } else {
      this.setData({
        title: '新增收件人'
      })
    }
    // this.getToken();
  },

  // // 获取access_token
  // getToken() {
  //   wx.request({
  //     url:
  //       'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=W0g3zCfydNC3tWtG0Y1wWFoF&client_secret=QFfqrGr9HzDcKV6gQQYuP9RMmyWCC4R8',
  //     method: 'POST',
  //     data: {},
  //     success: ({ data }) => {
  //       const access_token = data.access_token;
  //       if (access_token) {
  //         this.setData({
  //           access_token: access_token
  //         });
  //       }
  //       console.log(data);
  //     },
  //     fail: err => {
  //       console.log(err);
  //     }
  //   });
  // },

  // clearData() {
  //   this.setData({
  //     province: '',
  //     city: '',
  //     district: '',
  //     detailAddress: '',
  //     recipientName: '',
  //     phoneNumber: '',
  //     region: [],
  //   });
  // },
  clearAll() {
    this.setData({
      province: '',
      city: '',
      district: '',
      detailAddress: '',
      recipientName: '',
      phoneNumber: '',
      region: [],
    });
  },

  fieldChange(e) {
    const type = e.target.dataset.type;
    this.setData({
      [type]: this.trimAll(e.detail.value),
    });
    if (this.data.recipientName && this.data.phoneNumber.length === 11 && this.data.detailAddress && (this.data.province && this.data.city && this.data.district)) {
      this.setData({
        isDisabled: false
      })
    } else {
      this.setData({
        isDisabled: true
      })
    }
  },
  trimAll (str) {
    if (typeof str === 'string') {
      return str.split(/[\t\r\f\n\s]*/g).join('')
    } else {
      return str
    }
  },
  textareaFocus() {
    this.setData({
      isFocus: true    // 聚焦焦点
    })

  },
  // textareablur(){
  //   // 失去焦点 并且 值为空
  //   if(this.data.addressParseStr==''){
  //     this.setData({
  //       isFocus:false    // 失去焦点
  //     })
  //   }

  // },
  inputChange(e) {
    const type = e.target.dataset.type;
    this.setData({
      [type]: e.detail.value,
    });
  },

  clearAddressParse() {
    console.log(555);
    this.setData({
      addressParseStr: '',
    });
  },

  addressParse() {
    if (this.data.addressParseStr.trim()) {
      this.handleAddressRecognitionTwo(this.data.addressParseStr);
    }
  },

  handleAddressRecognitionTwo (val) {
    console.log("val:", val)
    textRecognition({
      text: val
    }).then(res => {
      if (res.resultStatus) {
        const result = res.resultData
        const obj = {
          province_name: result.province,
          city_name: result.city,
          county_name: result.county,
          town_name: result.town,
          detail: result.detail,
          name: result.person,
          mobile: result.phonenum
        }
        console.log("add-111:", obj)
        this.setRecipient(obj);
      }
    })
  },

  handleAddressRecognition(val) {
    // if (this.data.access_token) {
    if (this.data.discernFlag) {
      this.setData({
        discernFlag: false,
      });
      setTimeout(() => {
        this.setData({
          discernFlag: true,
        });
      }, 1000);
      let obj = {
        method: 'cloud.address.resolve',
        app_id: 107200,
        ts: Date.now(),
        api_key: '3beda353ef4d02ec0387e279cd06194407cb9b67',
      };
      wx.request({
        url: 'https://kop.kuaidihelp.com/api',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        data: {
          method: obj.method,
          app_id: obj.app_id,
          ts: obj.ts,
          sign: md5(obj.app_id + obj.method + obj.ts + obj.api_key),
          data: JSON.stringify({
            text: val,
            multimode: false,
            resolveTown: true,
          }),
        },
        success: ({ data }) => {
          console.log(data);
          if (!data.code) {
            let result = data.data[0];
            console.log(result);
            this.setRecipient(result);
          } else {
            wx.showToast({
              title: data.msg,
              icon: 'none',
              mask: true,
            });
          }
        },
      });
    }
    // } else {
    //   Toast('识别失败');
    // }
  },

  bindRegionChange(e) {
    const value = e.detail.value;
    this.setData({
      province: value[0],
      city: value[1],
      district: value[2],
      region: [value[0], value[1], value[2]],
    });
  },

  onSure() {
    console.log(this.data);
    if (!this.data.recipientName) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none',
      });
    } else if (!this.data.phoneNumber) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none',
      });
    } else if (this.data.phoneNumber.length !== 11) {
      wx.showToast({
        title: '手机号码长度为11位',
        icon: 'none',
      });
    } else if (!this.data.province || !this.data.city || !this.data.district) {
      wx.showToast({
        title: '请选择所在地区',
        icon: 'none',
      });
    } else if (!this.data.detailAddress) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none',
      });
    } else {
      this.setData({
        isDisabled: true,
        showOnSureDialog: true,//确认弹窗
      })
      // wx.showToast({
      //   title: '加载中...',
      //   icon: 'loading',
      // });

    }
  },
  toSave() {
    const obj = {
      recipientId: this.data.recipientId,
      province: this.data.province,
      city: this.data.city,
      district: this.data.district,
      detailAddress: this.data.detailAddress,
      recipientName: this.data.recipientName,
      phoneNumber: this.data.phoneNumber,
      recipientType: this.data.recipientType
    };


    // 调用接口提交
    setRecipients(obj).then((res) => {
      console.log("add-222", res)
      if (res.resultStatus) {
        wx.showToast({
          mask: true,
          title: this.data.recipientId == 0 ? '添加成功' : '编辑成功',
          icon: 'success',
          success: () => {
            if (this.data.recipientId) {
              app.globalData.modifyRecipient = {
                ...obj,
                phoneNumberSub:
                  obj.phoneNumber.substr(0, 3) +
                  '****' +
                  obj.phoneNumber.substr(7, 4),
              };
            }
            this.setData({
              showOnSureDialog: false,//确认弹窗
            })
            wx.navigateBack({
              delta: 1,
            });

            this.setData({
              isDisabled: false,
            })
          },
        });
      } else {
        Toast(res.errorMessage);
        this.setData({
          isDisabled: false,
        })
      }
    });

  },
  toEdit(){
    this.setData({
      showOnSureDialog: false,//关闭确认弹窗
    })

  },
  // 地址选中
  handleChoosed(e) {
    const chooseData = e.detail;
    const value = chooseData.map((item) => {
      return item.label;
    });
    this.setData({
      province: value[0],
      city: value[1],
      district: value[2],
      region: [value[0], value[1], value[2]],
    });
    if (this.data.recipientName && this.data.phoneNumber.length === 11 && this.data.detailAddress && (this.data.province && this.data.city && this.data.district)) {
      this.setData({
        isDisabled: false
      })
      console.log(2);
    } else {
      console.log(3);
      this.setData({
        isDisabled: true
      })
    }
  },
  handleClosePicker() {
    this.setData({
      showPicker: false,
    });
  },
  openPicker() {
    // this.setData({
    //   show: true
    // })
    this.setData({
      showPicker: true,
    });
  },
  //  拍照识别
  cameraPhoto() {

    console.log(111);
    const self = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        console.log(res, 'res')
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值
        // self.cropper.pushOrign(src)
        wx.navigateTo({
          url: `/packageAddress/pages/cutInside/cutInside?imgUrl=${src}`,
        })
      }
    })
  },
  // 设置收件人信息
  setRecipient(result) {
    console.log("这里是result");
    console.log(result)
    this.setData({
      // isFocus:false,
      // addressParseStr: '',
    })
    const obj = {
      province: result.province_name,
      city: result.city_name,
      district: result.county_name || result.town_name,
      detailAddress: (result.detail ? result.detail.trim() : ''),
      // (result.town_name ? result.town_name.trim() : '') +
      recipientName: result.name,
      phoneNumber: result.mobile,
      region: [],
    };
    // && result.county_name
    if (result.province_name && result.city_name && (result.county_name || result.town_name)) {
      obj.region = [
        result.province_name,
        result.city_name,
        (result.county_name || result.town_name),
      ];
    }
    
    // console.log("识别-obj", obj)
    if (obj.province && obj.city && obj.district && obj.detailAddress && (this.data.recipientName || obj.recipientName) && (this.data.phoneNumber || obj.phoneNumber) && obj.region) {
      this.setData({
        isDisabled: false,
        // isFocus:false
      })
    }

    //   二次过滤   空数据不覆盖
    let newObj = {};
    for (let key in obj) {
      if (obj[key].length) {
        newObj[key] = obj[key];
      }
    }
    this.setData(newObj);
  }
});
